<template>
  <div class="container">
    <div class="top-controls">
      <input type="file" @change="handleFileUpload" accept=".docx" />
    </div>
    <div class="main-content">
      <div class="left-panel">
        <ul v-if="tableOfContents.length">
          <TocItem 
            v-for="(item, index) in tableOfContents" 
            :key="item.id" 
            :item="item" 
            :on-scroll="scrollToSection" 
          />
        </ul>
      </div>
      <div class="right-panel">
        <WangEditorVue 
        v-model="editorContent" 
        placeholder="请输入富文本内容..." 
      />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref,onMounted, nextTick, watch, unref } from 'vue';
import mammoth from 'mammoth';
import docx2html from 'docx2html';
import WangEditor from './components/WangEditor.vue';
import WangEditorVue from './components/WangEditorVue.vue';
import TocItem from './components/TocItem.vue';

const editorContent = ref(''); // 存储编辑器内容
const originContent = ref(''); // 存储原始HTML内容
const tableOfContents = ref([]);
const sections = ref([]);
const handleFileUpload = async (e) => {
  const file = e.target.files[0];
  if (!file) return;

  const reader = new FileReader();
  reader.onload = async (event) => {
    const arrayBuffer = event.target.result;
    const result = await docx2html( arrayBuffer );
    console.log("Result:", result.content.outerHTML);
    // parseDocument(tempDiv.innerHTML);
    editorContent.value = ``;
  };
  reader.readAsArrayBuffer(file);
};

const parseDocument = (htmlContent) => {
  originContent.value = htmlContent;
  const newSections = [];
  const toc = [];
  let currentLevel = 0;
  const stack = [toc]; // 栈初始化为根目录数组
  const tempDiv = document.createElement('div');
  tempDiv.innerHTML = htmlContent;
  const elements = tempDiv.children;

  Array.from(elements).forEach((element, index) => {
    const level = getHeadingLevel(element.tagName);
    const id = `section-${index}`;

    if (level > 0) {
      element.id = id; // 为标题元素设置唯一id
      const title = element.textContent;
      const section = {
        id,
        level,
        title,
        content: '',
        children: []
      };

      // 调整栈长度匹配当前层级
      while (stack.length > level) stack.pop();
      const currentParent = stack[stack.length - 1]; // 获取当前层级的父级数组

      currentParent.push(section); // 添加到正确父级
      newSections.push(section);

      // 推送当前章节的子数组到栈，供下一级标题使用
      stack.push(section.children);

      currentLevel = level;
    } else {
      if (newSections.length > 0) {
        newSections[newSections.length - 1].content += element.outerHTML;
      }
    }
  });
  tableOfContents.value = toc;
  tableOfContents.value.unshift({
   children: [],content: "",id: "1",level: 1,title: "全文" 
  })
  sections.value = newSections;
  sections.value.unshift({
   children: [],content: "",id: "1",level: 1,title: "全文" 
  })
  editorContent.value = htmlContent; // 初始化编辑器内容为原始HTML
};

const getHeadingLevel = (tagName) => {
  if (tagName.startsWith('H') && tagName.length === 2) {
    return parseInt(tagName[1], 10);
  }
  return 0;
};

const scrollToSection = (id) => {
    // 查找对应的章节内容并更新编辑器，包含标题
    const section = sections.value.find(s => s.id === id);
    if (section) {
      if (!section.content && section.children && section.children.length == 0 && section.level == 1) {
        editorContent.value = originContent.value; // 清空编辑器内容
      } else {
        const headingTag = `h${section.level}`;
        const headingHtml = `<${headingTag}>${section.title}</${headingTag}>`;
        let contentHtml = section.content;

        // 递归生成多级子章节内容
        const generateContent = (node) => {
          const headingTag = `h${node.level}`;
          let html = `<${headingTag}>${node.title}</${headingTag}>`;
          html += node.content;
          if (node.children && node.children.length > 0) {
            html += node.children.map(child => generateContent(child)).join('');
          }
          return html;
        };

        // 处理content为空但有子章节的情况
        if (section.children && section.children.length > 0) {
          contentHtml = section.children.map(child => generateContent(child)).join('');
        }

        editorContent.value = headingHtml + contentHtml;
      }
    }
};




</script>

<style scoped>
.top-controls {
  display: flex;
  align-items: center;
  gap: 20px;
  margin-bottom: 20px;
}

.export-btn {
  padding: 8px 16px;
  background: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.export-btn:hover {
  background: #0056b3;
  text-decoration: none;
}

.container {
  padding: 20px;
}

.main-content {
  display: flex;
  margin-top: 20px;
  gap: 20px;
}

.left-panel {
  flex: 1;
  max-width: 300px;
  border-right: 1px solid #ccc;
  padding-right: 20px;
}

.right-panel {
  flex: 3;
}

button {
  background: none;
  border: none;
  text-align: left;
  cursor: pointer;
  color: #007bff;
  margin: 5px 0;
}

button:hover {
  text-decoration: underline;
}

ul {
  list-style-type: none;
  padding-left: 20px;
}

.toolbar {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  margin-bottom: 10px;
}

.editor {
  border: 1px solid #e8e8e8;
  border-radius: 4px;
  min-height: 500px;
  padding: 15px;
}
</style>

<style>
/* 全局样式确保v-html中的表格正确显示 */
.right-panel table {
  border-collapse: collapse;
  width: 100%;
  margin: 10px 0;
}
.right-panel td, .right-panel th {
  border: 1px solid #ddd;
  padding: 8px;
}
.right-panel tr:nth-child(even) {
  background-color: #f2f2f2;
}
  .right-panel p {
    margin: 10px 0;
    line-height: 1.6;
    font-size: 16px;
  }
</style>